package com.xexun.gpstracker.msg;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.xexun.gpstracker.AppContext;
import com.xexun.gpstracker.MainActivity;
import com.xexun.gpstracker.baby.activity.ChatActivity;
import com.xexun.gpstracker.baby.mytree.MyNode;
import com.xexun.gpstracker.baby.mytree.MyTreeListAdapter;
import com.xexun.gpstracker.baby.mytree.MyTreeSelectListAdapter;
import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.common.Constants;
import com.xexun.gpstracker.fix.swipemenu.SwipeMenu;
import com.xexun.gpstracker.fix.swipemenu.SwipeMenuCreator;
import com.xexun.gpstracker.fix.swipemenu.SwipeMenuItem;
import com.xexun.gpstracker.fix.swipemenu.SwipeMenuListView;
import com.xexun.gpstracker.msg.adapter.MsgAdapter;
import com.xexun.gpstracker.pojo.*;
import com.xexun.gpstracker.util.ByteUtil;
import com.xexun.gpstracker.util.CommUtil;
import com.xexun.gpstracker.util.HttpUtil;
import com.xexun.gpstracker.util.Utils;
import com.xexun.gpstracker.view.ClearEditText;
import com.xexun.gpstracker.vo.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.Subscriber;
import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.db.sqlite.SqlInfo;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.db.table.DbModel;
import org.xutils.ex.DbException;

import java.util.*;


/**
 * 消息界面
 */
public class MsgSelectFragment extends Fragment  {

    private boolean isFirst = true;
    ListView listView;
    private List<String> friends = new ArrayList<>();
    private ArrayAdapter<String> adapter;
    ClearEditText clearEditText;
    private boolean strangerFlag = false;   //联系人数据的标记（用于判断是否是陌生人）
    private boolean deviceFlag = false; //devie数据的标记，用来判读是否有重复数据

     MyTreeSelectListAdapter mAdapter;

    public static MsgSelectFragment newInstance() {
        return new MsgSelectFragment();
    }


    /**
     * 点击的回调接口
     */
    private OnSelectClickListener onSelectClickListener;


    public interface OnSelectClickListener
    {
        void onItemClick(AdapterView<?> parent, View view, int position, long id);
    }

    public void setOnSelectClickListener(OnSelectClickListener onSelectClickListener) {
        this.onSelectClickListener = onSelectClickListener;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_select_msg, container, false);


        listView = (ListView) view.findViewById(R.id.msg_select_listview);
        listView.setDivider(new ColorDrawable(0xE7E7E7));
        listView.setDividerHeight(1);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Toast.makeText(getActivity(),String.valueOf(position),Toast.LENGTH_LONG).show();

                if(onSelectClickListener != null){

                    onSelectClickListener.onItemClick(parent,view,position,id);

                }


            }
        });

//      listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        initTreeData();



        return view;
    }


    @Override
    public void onResume() {
        super.onResume();

//        init();
//        adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_single_choice,friends);
//        listView.setAdapter(adapter);
//        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    private void init() {
        friends.clear();
        List<Device> devices = Session.getInstance().getMonitors();

        if (CommUtil.isNotEmpty(devices)) {
            for (int i = 0; i < devices.size(); i++) {
                if (!devices.get(i).isBinded()) {
                    continue;
                }
                friends.add(devices.get(i).getName());
            }
        }

    }




    static final String TREEURL2 = Constants.baseUrl+"terminal/getDataNodesById";

    private void initTreeData(){
        Map<String,String> params = new HashMap<String, String>();

        HttpUtil.get(TREEURL2, params, new Callback.ProgressCallback<JSONObject>() {
            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {

            }

            @Override
            public void onSuccess(JSONObject result) {

                try {
                    JSONArray jsonArray =  result.getJSONArray("body");
                    if(jsonArray == null){
                        return;
                    }

                    List<MyNode> mDatas = new ArrayList<MyNode>();

                    for(int i = 0 ; i<jsonArray.length() ;i++){


                        JSONObject obj = jsonArray.getJSONObject(i);
                        //String parentId, String nodeId, String name,int depth,Boolean expand,Boolean hasChildren
                        MyNode nodeBean = new MyNode("-1",obj.optString("id"),obj.getString("name"),0,true,true,"");
                        mDatas.add(nodeBean);
                    }

                    mAdapter = new MyTreeSelectListAdapter(listView, getActivity(), mDatas);
                    listView.setAdapter(mAdapter);
                    initAdapter(listView);



                    listView.performItemClick(listView.getAdapter().getView(0, null, null), 0, listView.getItemIdAtPosition(0));

                   listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);


                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }




    //初始化tree adapter
    private void initAdapter(final ListView mTree){

        mAdapter.setOnTreeNodeClickListener(new MyTreeSelectListAdapter.OnTreeNodeClickListener() {
            @Override
            public void onClick(MyNode node, int position) {


            }
        });

    }


}
